package com.yyw.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;

import com.yyw.bean.User;
import com.yyw.util.ResultFactory;

import lombok.extern.slf4j.Slf4j;

@WebFilter(urlPatterns = { "/user/*" }, filterName = "001")
@Slf4j
public class LoginFilter implements Filter {

    @Value("${my.session.user}")
    private String userAttr;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

//        log.info("权限filter启动...");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest re = (HttpServletRequest) request;
        User user = (User) re.getSession().getAttribute(userAttr);

        if (user == null) {
//            log.info("拦截-" + userAttr + "\n" + user.toString());
            PrintWriter writer = response.getWriter();
            writer.print(ResultFactory.result(401, "未登录"));
            writer.flush();
            writer.close();
        } else {
            chain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

}
